#include <func.h>
#include <crypt.h>
#include <shadow.h>

#define MAXLINE 1024

void get_salt(char *salt,char *passwd)
{
    int i,j,num=0;
    //取出salt,i记录密码字符下标,j记录$出现次数
    for(i=0;passwd[i]!='\0';++i)
    {
        if(passwd[i] == '$')
            num++;
    }
    for(i=0,j=0;j<num;i++){
        if(passwd[i]=='$')
            j++;
    }
    strncpy(salt,passwd,i-1);
}

void Entry_Check(void)
{
    struct spwd *sp;
    char salt[MAXLINE]={0}; 
    char name[MAXLINE]="",passwd[MAXLINE]="";
    printf("请输入用户名:");
    scanf("%s",name);
    //printf("INFO:name= %s\n",name);
    
    sp = getspnam(name);
    if(sp==NULL){
        error(1,0,"gets name and passwd failed");
    }

    printf("请输入密码:");
    scanf("%s",passwd);

    get_salt(salt,sp->sp_pwdp);
    char*encrypt_message = crypt(passwd,salt);
    if(strcmp(encrypt_message,sp->sp_pwdp)==0){
        printf("登陆成功\n");
    }
    else{
        printf("登录失败,密码错误\n");
    }
    char path[MAXLINE]="/home";
    strcat(path,"/");
    strcat(path,name);
    chdir(path);
}

